package jumpingnotes.restlet.resource;

import static jumpingnotes.restlet.ErrorCode.NO_PERMISSION;
import static jumpingnotes.restlet.ErrorCode.OBJECT_NOT_FOUND;
import static jumpingnotes.restlet.ErrorCode.SERVER_INTERNAL_ERROR;

import java.lang.reflect.Method;

import jumpingnotes.model.entity.Member;
import jumpingnotes.restlet.JsonMapping;
import jumpingnotes.service.QueryService;

import org.json.JSONObject;
import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.ResourceException;
import org.restlet.resource.Variant;

public class FindByIdResource extends BaseResource
{
	private Class<?> type = null;
	private int id;

	@Override
	public void init(Context context, Request request, Response response)
	{
		super.init(context, request, response);

		getVariants().add(new Variant(MediaType.APPLICATION_JSON));

		try
		{
			sessionId = (String) getRequest().getAttributes().get("sessionId");
			checkPermission();

			if (hasPermission())
			{
				// URL: "/{types}/{id}"
				String typesStr = (String) getRequest().getAttributes().get("types");
				String idStr = (String) getRequest().getAttributes().get("id");

				type = getTypeByName(typesStr);

				if ("me".equalsIgnoreCase(idStr))
				{
					String email = session.getEmail();
					Member member = service.findMemberByEmail(email);
					id = member.getMemberId();
				}
				else
				{
					id = Integer.valueOf(idStr);
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public Representation represent(Variant variant) throws ResourceException
	{
		if (!hasPermission())
		{
			return createErrorRepresentation(NO_PERMISSION);
		}

		if (type == null)
		{
			return createErrorRepresentation(OBJECT_NOT_FOUND);
		}

		try
		{
			String methodName = "find" + type.getSimpleName() + "ById";
			Method method = QueryService.class.getMethod(methodName, int.class);
			Object object = method.invoke(service, id);

			if (object == null)
			{
				return createErrorRepresentation(OBJECT_NOT_FOUND);
			}

			JSONObject objectJson = JsonMapping.map(type, object);
			return createJsonRepresentation(objectJson);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return createErrorRepresentation(SERVER_INTERNAL_ERROR);
		}
	}
}
